/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ca.trader.utils;

import org.jasypt.util.password.StrongPasswordEncryptor;
import java.security.SecureRandom;
import ca.trader.logger.TraderLogger;
import ca.trader.user.DoAuthenticate;

/**
 * Utility for passwords
 * @author Ahsan
 */
public class PasswordUtils
{
	 private static final String _className = PasswordUtils.class.getName();

	 /**
	  * Crypts a cleartext password.
	  * @param password the cleartext password
	  * @return  the crypted password
	  */
	 
	 private static String generateSalt ()
	 {
		  int asciiBigA = (int) 'A';
		  int asciiSmallZ = (int) 'z';
		  final int passwordLength = 8;
		  SecureRandom random = new SecureRandom();
		  int randomAscii;
		  char randomChar; 
		  StringBuffer sb = new StringBuffer (passwordLength);
		  
		  for (int i = 0; i < passwordLength; i++)
		  {
			   randomAscii = random.nextInt(asciiSmallZ - asciiBigA + 1);
			   randomChar = (char) (asciiBigA + randomAscii);
			   sb.append (randomChar);			   
		  }
		  
		  return sb.toString();
	 }
	 
	 public static String cryptPasswordString(String password)
	 {
		  StrongPasswordEncryptor passwordEncryptor = new StrongPasswordEncryptor();
		  
		  String salt = generateSalt();
		  		  
		  String encryptedPassword = passwordEncryptor.encryptPassword(salt + password);
		  return salt + ":" + encryptedPassword;
	 }

	 /**
	  * tests if an uncrypted password matches a crypted password
	  * @param userUncryptedPassword the uncrypted password
	  * @param cryptedPassword the crypted password
	  * @return  if the uncrypted password matches the crypted password
	  */
	 public static boolean testCryptedPassword(String userUncryptedPassword, String cryptedPasswordWithSalt)
	 {
		  StrongPasswordEncryptor passwordEncryptor = new StrongPasswordEncryptor();
		  
		  String salt, encryptedPassword;
		  salt = cryptedPasswordWithSalt.split (":")[0];		  
		  encryptedPassword = cryptedPasswordWithSalt.split (":")[1];
		  
		  return passwordEncryptor.checkPassword(salt + userUncryptedPassword, encryptedPassword);
	 }

}
